package com.jobsika.client.search;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.jobsika.client.Util;
import com.jobsika.domain.RPCPost;
import com.jobsika.domain.RPCUser;

public class SearchResultPanel extends Composite {
	private VerticalPanel skeleton;
	private Button more;
	private int type = 0;
	private int page = 0;
	private String query = "";
	private int limit = 10;
	
	public SearchResultPanel(int limit) {
		skeleton = new VerticalPanel();
		more = new Button("More");
		
		more.addClickHandler(moreClick);
		more.addStyleName("search-more");

		skeleton.setStyleName("searchResultPanel");
		
		this.limit = limit;
		this.initWidget(skeleton);
	}

	private ClickHandler moreClick = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			switch (type) {
				case 0:
					page += 1;
					History.newItem(Util.QUERY+"="+query+"&"+Util.PAGE+"="+page+"&"+Util.ADD+"=1");
					break;
				case 1:
					History.newItem(Util.USER+"&"+Util.ADD+"=1");
					break;
			}
			History.fireCurrentHistoryState();
		}
	};
	
	public int size() {
		return skeleton.getWidgetCount();
	}
	
	public void setPosts(String query, int page, int add, RPCPost[] posts) {
		if (add == 0) {
			skeleton.clear();
			Window.scrollTo(0, 0);
		} else {
			skeleton.remove(more);
		}
		postAction(query, page, posts);
	}
	
	public void postAction(String query, int page, RPCPost[] posts) {
		this.type = 0;
		this.page = page;
		this.query = query;
		for (RPCPost post : posts) {
			this.addSearchItem(post);
		}
		if (posts.length >= limit) {
			this.skeleton.add(more);
		}
	}
	
	public void setUsers(String query, int page, int add, RPCUser[] users) {
		if (add == 0) {
			skeleton.clear();
		} else {
			skeleton.remove(more);
		}
		userAction(query, page, users);
	}
	
	public void userAction(String query, int page, RPCUser[] users) {
		type = 1;
		for (RPCUser user : users) {
			this.addSearchItem(user);
		}
		if (users.length >= limit) {
			this.skeleton.add(more);
		}
	}
	
	public void addSearchItem(RPCPost post) {
		SearchItem item = new SearchItem(post);
		skeleton.add(item);
	}
	
	public void addSearchItem(RPCUser user) {
		SearchItem item = new SearchItem(user);
		skeleton.add(item);
	}

	public void addSearchItem(SearchItem item) {
		skeleton.add(item);
	}
}
